package com.hgx.web.service.restful.client;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SuppressWarnings("all")
public class RestPostClientMain {

    public static void main(String[] args) throws ClientProtocolException, IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost("http://localhost:8080/studentServce/rest/student");

        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();

        list.add(new BasicNameValuePair("number", "0202"));
        list.add(new BasicNameValuePair("name", "张三"));
        list.add(new BasicNameValuePair("age", "19"));
        list.add(new BasicNameValuePair("birth", Date.from(Instant.now()).toString())) ;


        HttpEntity httpEntity = new UrlEncodedFormEntity(list, "utf-8");

        httpPost.setEntity(httpEntity);

        HttpResponse httpResponse = httpClient.execute(httpPost);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");

            System.out.println(result);

            EntityUtils.consume(entity);
        } else {
            System.err.println(httpResponse.getStatusLine());
        }
        httpClient.close();

    }

}
